<template>
  <div class="">
    <!--    <input type="file" ref="uploadFile" accept=".jpg, .jpeg, .png" style="position: fixed;left: 100%;"-->
    <!--           @change="uploadedFile"/>-->
    <div class="cardHeader">
      <img class="cardHeader_icon m_hoverCP" src="@assets/img/img28.png" alt="" @click="onBack"/>
      <span class="m_hoverCP" @click="onBack">{{$t('message.Return')}}</span>
    </div>
    <section class="contentBox">
      <section class="content_left">
        <a-spin :spinning="savaLoading" :tip="$t('message.Saving')">
          <div class="box1">
            <div class="box1_text">{{$t('message.Product_information')}}</div>
            <div class="box1_btn2 m_hoverCP" @click="onEditEnd" v-if="isEdit">{{$t('message.Complete')}}</div>
            <div class="box1_btn m_hoverCP" @click="onEdit" v-else>
              <img class="box1_btn_icon " src="@assets/img/img36.png" alt=""/>{{$t('message.Edit')}}
            </div>
          </div>
          <j-image-upload class="content_left_img" v-model="formObj.productPic"
                          :disabled="!isEdit"></j-image-upload>
          <section class="box2">
            <div class="box2_item" style="width: 100%">
              <div class="box2_item_label">{{$t('message.Product_name')}}:</div>
              <div class="box2_item_text" v-if="isEdit">
                <a-input v-model="formObj.productName" allowClear placeholder="请输入"></a-input>
              </div>
              <div class="box2_item_text" v-else>{{ formObj.productName }}</div>
            </div>
            <div class="box2_item">
              <div class="box2_item_label">{{$t('message.Specifications_and_models')}}:</div>
              <div class="box2_item_text" v-if="isEdit">
                <a-input v-model="formObj.productSpecification" allowClear placeholder="请输入"></a-input>
              </div>
              <div class="box2_item_text" v-else>{{ formObj.productSpecification }}</div>
            </div>
            <!-- <div class="box2_item">
              <div class="box2_item_label">{{$t('message.Product_NO')}}:</div>
              <div class="box2_item_text" v-if="isEdit">
                <a-input v-model="formObj.productCode" allowClear placeholder="请输入"></a-input>
              </div>
              <div class="box2_item_text" v-else>{{ formObj.productCode }}</div>
            </div> -->
            <div class="box2_item">
              <div class="box2_item_label">{{$t('message.Unit')}}:</div>
              <div class="box2_item_text" v-if="isEdit">
                <a-select v-model="formObj.productUnitId" allowClear placeholder="请选择"
                          @change="onChangeProductUnitId" style="width: 100%;">
                  <a-select-opt-group :key="key" :value="key" :label="key"
                                      v-for="(value, key, index) in getAllUnitByGroupData">
                    <a-select-option :key="itemA.id" :value="itemA.id" v-for="(itemA,indexA) in value">
                      {{ itemA.unitCode }}
                    </a-select-option>
                  </a-select-opt-group>
                </a-select>
              </div>
              <div class="box2_item_text" v-else>{{ formObj.productUnitName }}</div>
            </div>
            <div class="box2_item">
              <div class="box2_item_label">{{$t('message.Product_weight')}}:</div>
              <div class="box2_item_text" v-if="isEdit">
                <a-input-number v-model="formObj.productWeight" allowClear placeholder="请输入"
                                :step="0.01" :precision="2" style="width: 100%;"></a-input-number>
              </div>
              <div class="box2_item_text" v-else>{{ formObj.productWeight }}{{ formObj.productWeightUnit }}</div>
            </div>
            <div class="box3_item">
              <div class="box2_item_label">{{$t('message.Product_Introduction')}}:</div>
              <div class="box2_item_text" v-if="isEdit">
                <div style="position: relative" class="flexOne">
                <textarea
                  v-model="formObj.productIntroduction"
                  class="textarea flexOne"
                  placeholder="请输入内容"
                  name=""
                  id=""
                  cols="30"
                  rows="10"
                ></textarea>
                <div class="length">
                  {{
                    formObj.productIntroduction.length
                  }}/500
                </div>
              </div>
              </div>
              <div class="box2_item_text" v-else>{{ formObj.productIntroduction }}</div>
            </div>
          </section>
        </a-spin>
        <!-- <div class="content_left_btnBox m_cbFlex">
          <a-button type="link" :disabled="ProductI == 0 || isEdit" @click="onLast">
            <a-icon type="left" style="transform: translateY(1px);"/>
            上一个
          </a-button>
          <a-button type="link" :disabled="ProductI == currentLength - 1 || isEdit" @click="onNext">
            下一个
            <a-icon type="right" style="transform: translateY(1px);"/>
          </a-button>
        </div> -->
      </section>
      <section class="content_right">
        <div class="box3">
          <div class="box3_text">{{$t('message.Product_carbon_footprint')}}</div>
          <div class="box3_btn m_hoverCP" @click="onAdd">{{$t('message.new_accounting')}}
          </div>
        </div>
        <div class="tabBox">
          <a-tabs :activeKey="activeKey" @change="onChangeActiveKey">
            <a-tab-pane key="all" :tab="$t('message.All')"></a-tab-pane>
            <a-tab-pane key="1" :tab="$t('message.Accounting_has_been_created')"></a-tab-pane>
            <a-tab-pane key="2" :tab="$t('message.Model_creation')"></a-tab-pane>
            <a-tab-pane key="3" :tab="$t('message.Accounting_completion')"></a-tab-pane>
            <a-tab-pane key="4" :tab="$t('message.Archived')"></a-tab-pane>
          </a-tabs>
          <div class="tabInnerBox" v-if="getCalculateListData && getCalculateListData.length > 0">
            <div class="itemBox" v-for="(item,index) in getCalculateListData" :key="index">
              <itemCard :item="item" @back="getData" @copy="onCopy" @detail="onDetail"/>
            </div>
          </div>
        </div>
      </section>
    </section>
    <!-- 详情弹窗 -->
    <section class="m_popupBox" v-if="isShowFormPopup">
      <footprintProductForm ref="footprintProductForm" @back="footprintProductFormBack"></footprintProductForm>
    </section>
  </div>
</template>

<script>
import {getAction, getFileAccessHttpUrl, postAction, uploadAction} from '@/api/manage'
import itemCard from '@views/module_footprint/footprintProductView/modules/itemCard.vue'
import footprintProductForm from '@views/module_footprint/footprintProductView/modules/footprintProductForm.vue'

export default {
  name: 'footprintProductDetail',
  components: {
    itemCard,
    footprintProductForm,
  },
  data() {
    return {
      isEdit: false,
      formObj: {},
      activeKey: 'all', // all全部 1已创建核算 2模型创建中 3核算完成
      getCalculateListData: [], // 核算列表数据
      fangLianDian: true, // 防连点
      isShowFormPopup: false, // 是否显示表单弹窗
      // uploadLoading: false, // 上传图片加载框
      savaLoading: false, // 保存产品数据加载框
      ProductI: 0, // 当前产品下标
      ProductS: [], // 当前产品
      getAllUnitByGroupData: {}, // 单位分组数据
    };
  },
  computed: {
    currentLength() {
      return this.ProductS ? this.ProductS.length : 0
    },
  },
  created() {
  },
  methods: {
    getAvatarView: function (avatar) {
      return getFileAccessHttpUrl(avatar)
    },
    /**
     * 上一个产品
     */
    onLast() {
      this.ProductI = this.ProductI - 1
      this.getData()
    },
    /**
     * 下一个产品
     */
    onNext() {
      this.ProductI = this.ProductI + 1
      this.getData()
    },
    // uploadedFile(e) {
    //   console.log('fileinfo', e, e.target.files)
    //   if (e.target.files && e.target.files.length > 0) {
    //     let blobInfo = e.target.files[0];
    //     console.log('fileinfo', blobInfo)
    //     const formData = new FormData();
    //     formData.append("file", blobInfo);
    //     this.uploadLoading = true
    //     uploadAction('/sys/common/upload', formData).then((res) => {
    //       if (res.success) {
    //         this.formObj.productPic = res.message
    //       }
    //     }).finally(() => {
    //       this.uploadLoading = false
    //     });
    //   }
    // },
    // onUpload() {
    //   if (this.isEdit) {
    //     this.$refs.uploadFile.click()
    //   }
    // },
    /**
     * 切换tab
     * @param key all全部 1已创建核算 2模型创建中 3核算完成
     */
    onChangeActiveKey(key) {
      console.log('onChangeActiveKey', key);
      this.activeKey = key
      this.getData()
    },
    /**
     * 核算表单回调
     */
    footprintProductFormBack() {
      this.isShowFormPopup = false
      this.getData()
    },
    /**
     * 复制核算成功触发
     */
    onCopy() {
      this.getData('copy')
    },
    /**
     * 核算详情/核算编辑
     * @param item
     */
    onDetail(item, copy) {
      console.log('onDetail', item)
      this.isShowFormPopup = true

      this.$nextTick(() => {
        console.log('onDetail', this.$refs)
        let theObj = {
          productId: this.formObj.id,
          productName: this.formObj.productName,
          functionalUnit: item.functionalUnit,
          batchNumber:  item.batchNumber,
          productUnitId: this.formObj.productUnitId,
          productUnitName: this.formObj.productUnitName,
          calculateNumber: item.calculateNumber,
          dataRange: [item.beginTime, item.endTime],
          beginTime: item.beginTime,
          endTime: item.endTime,
          lifeCycleType: item.lifeCycleType,
          flowChart: item.flowChart,
          id: item.id,
          calculateArchived: item.calculateArchived, // 是否归档
          reportAddress: item.reportAddress, // 第三步查看碳足迹报告链接
        }
        if (item.lifeCycleType == 3) {
          theObj.cacheLifeCycleItem = item.lifeCycleItem.split(',')
        }
        console.log('theObj', theObj)
        console.log('this.$refs', this.$refs)
        this.$set(this.$refs.footprintProductForm, 'queryParam', theObj)
        this.$refs.footprintProductForm.getData()
        let step = ''
        if (copy) {
          // 复制并打开详情到第一阶段
          step = 1
        } else {
          // 打开详情到当前阶段
          step = item.calculateStatus
        }
        this.$refs.footprintProductForm.onChangeStep(step, item.calculateArchived === '1')
      })
    
    },
    /**
     * 添加核算
     */
    onAdd() {
      console.log('onAdd')
      this.isShowFormPopup = true
      this.$nextTick(() => {
        console.log('onAdd', this.$refs)
        this.$refs.footprintProductForm.queryParam.productId = this.formObj.id
        this.$refs.footprintProductForm.queryParam.productName = this.formObj.productName
        this.$refs.footprintProductForm.queryParam.productUnitId = this.formObj.productUnitId
        this.$refs.footprintProductForm.queryParam.productUnitName = this.formObj.productUnitName
        this.$refs.footprintProductForm.getData()
      })
    },
    getData(copy) {
      this.$set(this, 'formObj', this.ProductS[this.ProductI])
      // 单位
      getAction('/emission/factor/cyEmissionUnit/getAllUnitByGroup').then((res) => {
        if (res.success) {
          this.getAllUnitByGroupData = res.result || {}
        }
      });
      // 核算数据
      let reqData = {
        productId: this.formObj.id,
      }
      if (this.activeKey != 'all') {
        reqData.calculateStatus = this.activeKey
      }
      this.getCalculateListData = []
      this.fangLianDian = false
      getAction('/footprintProduct/cyFootprintProduct/getCalculateList', reqData).then((res) => {
        if (res.success) {
          let resData = res.result || []
          // 计算每一条的总碳排
          resData.forEach(item => {
            let totalCarbonEmission = 0
            if (item.calculateLifeCycle && item.calculateLifeCycle.length > 0) {
              item.calculateLifeCycle.forEach(itemA => {
                totalCarbonEmission = totalCarbonEmission + itemA.carbonEmission
              })
            }
            item.totalCarbonEmission = totalCarbonEmission
          })
          this.getCalculateListData = resData
          if (copy) {
            // 复制核算后，打开详情，跳转到第一阶段
            this.onDetail(this.getCalculateListData[0], 'copy')
          }
        }
      }).finally(() => {
        this.fangLianDian = true
      })
    },
    // ============================================================编辑产品
    /**
     * 编辑产品单位
     */
    onChangeProductUnitId(e) {
      console.log('onChangeProductUnitId', e, this.getAllUnitByGroupData)
      for (let key in this.getAllUnitByGroupData) {
        let value = this.getAllUnitByGroupData[key]
        for (let index = 0; index < value.length; index++) {
          if (value[index].id == e) {
            this.formObj.productUnitName = value[index].unitCode
          }
        }
      }
    },
    /**
     * 编辑产品
     */
    onEdit() {
      console.log('onEdit')
      this.isEdit = true
    },
    /**
     * 检查编辑产品表单数据
     */
    checkFormData() {
      if (!this.formObj.productName) {
        this.$message.warn(this.$t('message.please_select_product_name'))
        return false
      }
      // if (!this.formObj.productCode) {
      //   this.$message.warn(this.$t('message.please_select_product_NO'))
      //   return false
      // }
      if (!this.formObj.productSpecification) {
        this.$message.warn(this.$t('message.please_enter_specification_model'))
        return false
      }
      if (!this.formObj.productUnitId) {
        this.$message.warn(this.$t('message.please_select_unit'))
        return false
      }
      if (!this.formObj.productWeight) {
        this.$message.warn(this.$t('message.please_select_weight'))
        return false
      }
      return true
    },
    /**
     * 确定编辑产品
     */
    onEditEnd() {
      console.log('onEditEnd')
      if (this.checkFormData()) {
        this.savaLoading = true
        postAction('/footprintProduct/cyFootprintProduct/saveProduct', this.formObj).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.isEdit = false
            this.$emit('update')
          }
        }).finally(() => {
          this.savaLoading = false
        });
      }
    },
    // ============================================================通用

    throttle(func, wait) {
      let lastTime = 0;
      return function (...args) {
        const now = Date.now();
        if (now - lastTime >= wait) {
          lastTime = now;
          func.apply(this, args);
        }
      };
    },
    debounce(func, delay) {
      let timer;
      return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, arguments);
        }, delay);
      };
    },
    /**
     * 返回上一级
     */
    onBack() {
      if (this.fangLianDian) {
        this.$emit('back')
      }
    },
  },
};

</script>

<style lang="less" scoped>
&:focus-visible {
  outline: 0px;
}
.length {
  font-weight: 400;
  font-size: 12px;
  color: #888888;
  position: absolute;
  right: 8px;
  bottom: 10px;
}
.textarea {
  width: 100%;
  height: 119px;
  font-weight: 400;
  font-size: 14px;
  border: 1px solid #dcdcdc;
  color: #333333;
  resize: none;
  padding: 8px;
}
.flexOne {
  flex: 1;
}
///deep/ .ant-input-affix-wrapper {
//  background: #F6F6F6 !important;
//}

.content_left_img{
  /deep/ .ant-upload-list-picture-card-container {
  width: 229px;
  height: 196px;
}

/deep/ .ant-upload-list-picture-card .ant-upload-list-item {
  width: 229px;
  height: 196px;
}

/deep/ .ant-upload.ant-upload-select-picture-card {
  width: 229px;
  height: 196px;
}
}



.cardHeader {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #000000;

  .cardHeader_icon {
    width: 16px;
    height: 16px;
  }
}

.contentBox {
  margin-top: 24px;
  display: flex;
  gap: 24px;

  .content_left {
    position: relative;
    box-sizing: border-box;
    width: 410px;
    padding: 24px;
    background: #FFFFFF;
    height: calc(100vh - 59px - 24px - 24px - 24px - 21px);
  }

  .content_left_img {
    display: block;
    margin: 24px auto 0;
    width: 229px;
    height: 196px;
  }

  .content_left_btnBox {
    position: absolute;
    left: 24px;
    bottom: 24px;
    width: 362px;
  }

  .content_right {
    flex: 1;
    padding: 24px;
    background: #FFFFFF;
  }

}

.box1 {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .box1_text {
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 16px;
    color: #333333;
  }

  .box1_btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    width: 79px;
    height: 24px;
    border-radius: 3px;
    border: 1px solid #888888;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #333333;

    img {
      width: 14px;
      height: 14px;
    }
  }

  .box1_btn2 {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 59px;
    height: 24px;
    background: #FFFFFF;
    border-radius: 3px;
    border: 1px solid #148958;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #148958;
  }

}


.box2 {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;

  .box2_item {
    width: 49%;
    margin-top: 24px;
  }
  
  .box3_item {
    width: 100%;
    margin-top: 24px;
  }
  .box2_item_label {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #777777;
  }

  .box2_item_text {
    margin-top: 8px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
  }
}


.box3 {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .box3_text {
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 16px;
    color: #333333;
  }

  .box3_btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 115px;
    height: 32px;
    background: #148958;
    border-radius: 3px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.9);
  }
}

.tabBox {
  .tabInnerBox {
    padding: 8px 0 0;
  }

  .itemBox {
    margin-bottom: 24px;
  }

  .itemBox:last-child {
    margin-bottom: 0;
  }
}


</style>
